package com.wuye.web;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsPSMDetector;

import java.io.IOException;

/**
 * Created by xieyp on 2016-03-12.
 */
public class CharsetDetector {
    private boolean found = false;
    public String encoding = null;

    public CharsetDetector(byte[] buf) throws IOException {
        nsDetector det = new nsDetector(nsPSMDetector.ALL);
        det.Init(charset -> {
            encoding = charset;
            found = true;
        });
        boolean isAscii = det.isAscii(buf, buf.length);
        if (!isAscii) {
            det.DoIt(buf, buf.length, false);
        }
        det.DataEnd();
        if (isAscii) {
            encoding = "ASCII";
            found = true;
        }
        if (!found) {
            String[] prob = det.getProbableCharsets();
            if (prob != null && prob.length >= 1) ;
            encoding = prob[0];
        }
    }
}
